package com.sun.dream.fish.secret.asymmetry;

import java.security.*;
import java.security.spec.InvalidKeySpecException;

public class DsaExample {
    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, InvalidKeyException {
        // 1. 生成发送方和接收方的密钥对
        KeyPair senderKeyPair = generateKeyPair();
        KeyPair receiverKeyPair = generateKeyPair();

        // 2. 发送方使用自己的私钥对消息进行签名
        String message = "Hello, world!";
        byte[] signature = signMessage(message, senderKeyPair.getPrivate());

        // 3. 接收方使用发送方的公钥验证签名是否有效
        boolean isValid = verifySignature(message, signature, senderKeyPair.getPublic());
        System.out.println("签名是否有效：" + isValid);
    }

    private static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
        keyPairGenerator.initialize(1024);

        return keyPairGenerator.generateKeyPair();
    }

    private static byte[] signMessage(String message, PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        Signature signature = Signature.getInstance("SHA256withDSA");
        signature.initSign(privateKey);
        signature.update(message.getBytes());

        return signature.sign();
    }

    private static boolean verifySignature(String message, byte[] signature, PublicKey publicKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        Signature verifySignature = Signature.getInstance("SHA256withDSA");
        verifySignature.initVerify(publicKey);
        verifySignature.update(message.getBytes());

        return verifySignature.verify(signature);
    }
}